<template>
  <a-button
    v-bind="$attrs"
    :disabled="isStart"
    @click="handleStart"
    :loading="loading"
    class="customer-btn"
  >
    {{ !isStart? `获取验证码` : `${currentCount}秒后重新获取` }}
  </a-button>
</template>
<script lang="ts">
import { defineComponent, ref, PropType, watchEffect } from "vue";
import { useCountdown } from "./useCountdown";
import { isFunction } from "@/utils/is";
export default defineComponent({
  props: {
    value: {
      type: String,
    },
    count: {
      type: Number,
      default: 60,
    },
    beforeStartFunc: {
      type: Function as PropType<() => boolean>,
      default: null,
    },
  },
  setup(props) {
    const loading = ref(false);
    const { currentCount, isStart, start, reset } = useCountdown(props.count);
    watchEffect(() => {
      props.value === undefined && reset();
    });
    async function handleStart() {
      const { beforeStartFunc } = props;
      if (beforeStartFunc && isFunction(beforeStartFunc)) {
        loading.value = true;
        try {
          const canStart = await beforeStartFunc();
          canStart && start();
        } finally {
          loading.value = false;
        }
      } else {
        start();
      }
    }
    return { loading, handleStart, currentCount, isStart };
  },
});
</script>
<style lang="scss" scoped>
.ant-btn {
  border: 0;
}
</style>
